package com.wanxi.tcp.demo6理解客户端和服务器相互发送数据;

import java.io.*;
import java.net.Socket;

/**
 * TCP 客户端,演示客户端可以不断的跟服务器端说话，服务器也能应答,同时客户端输入886进行关闭
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        System.out.println("tcp 客户端启动......");
        //1 创建客户端socket
        Socket clientSocket = new Socket("127.0.0.1", 30000);
        //2 准备发送的信息
        String message = "";
        //3 创建控制台输入流
        BufferedReader controlReader = new BufferedReader(new InputStreamReader(System.in));
        //4 创建接收服务器端的输入流
        BufferedReader receiveReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        while (true) {
            // 5接收客户端控制台输入的内容，可以优化到if (message != null)这里
            message = controlReader.readLine();
            if (message != null) {
                // 6客户端说拜拜
                if (!message.equals("886")) {
                    //3 发送信息
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                    writer.write(message);
                    writer.newLine();
                    writer.flush();
                    // 7发送完毕后，接收信息服务发送的信息
                    String receiveMessage = receiveReader.readLine();
                    if (receiveMessage != null) {
                        System.out.println("服务器对我说：" + receiveMessage);
                    }
                } else {
                    controlReader.close();
                    clientSocket.close();// 关闭连接
                    return;
                }
            }
        }
    }
}
